from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.utils.deprecation import MiddlewareMixin

from utils.response import BaseResponse


class UserInfo(object):
    def __init__(self, role, username, id):
        self.role = role
        self.username = username
        self.id = id
        self.menu_name = None
        self.text_list = None


class AuthMiddleware(MiddlewareMixin):

    def process_white_url(self, request):
        if request.path_info in settings.NB_WHITE_URL:
            return True
        else:
            return False

    def process_request(self, request):
        """
        校验用户是否已登陆
        1. user_dict：session中获取当前用户信息
        2. 未登录,跳转回当前页面
        3. request.nb_user:已登录,封装user_dict,以共后续函数使用
        4. return None
        """
        if self.process_white_url(request):
            return None

        # {'role': 'ADMIN', 'username': 'root', 'id': 2}
        user_dict = request.session.get(settings.NB_SESSION_KEY)

        # 未登录跳转回当前页面
        if not user_dict:
            return redirect(settings.LOGIN_URL)
        request.nb_user = UserInfo(**user_dict)
        # return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        """
        校验用户是否有权限访问当前页面
        1. 获取当前登录角色所拥有的所有权限
        2. 获取该角色访问该页面的权限
        3. 判断当前用户角色是否包含当前访问页面的权限
        4. return None
        """
        if self.process_white_url(request):
            return None
        # 公共权限
        current_name = request.resolver_match.url_name
        if current_name in settings.NB_PERMISSION_PUBLIC:
            return None

        user_permission_dict = settings.NB_PERMISSION[request.nb_user.role]

        # 判断当前用户类型是否有访问的该页面的权限
        if current_name not in user_permission_dict:
            if request.is_ajax():
                return JsonResponse({'status': False, 'detail': '无权访问'})
            return render(request, 'permission.html')

        menu_name = current_name
        text_list = []  # ['创建订单']
        text_list.append(user_permission_dict[current_name]['text'])
        while user_permission_dict[menu_name]['parent']:
            menu_name = user_permission_dict[menu_name]['parent']
            text_list.append(user_permission_dict[menu_name]['text'])

        # 当前最顶级父级菜单的值
        request.nb_user.menu_name = menu_name

        # 路径导航
        # if settings.NB_MENU[request.nb_user.role]['children']['text']==menu_name:
        #     text = settings.NB_MENU[request.nb_user.role]
        text_list.reverse()  # 反转
        request.nb_user.text_list = text_list
        return None
